package com.ytkj.digitalConstruction.controller.assets;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ytkj.digitalConstruction.HttpResult;
import com.ytkj.digitalConstruction.ReturnCode;
import com.ytkj.digitalConstruction.entity.assets.Device;
import com.ytkj.digitalConstruction.enums.asset.AssetStatus;
import com.ytkj.digitalConstruction.httpbean.PageParam;
import com.ytkj.digitalConstruction.httpbean.PageResult;
import com.ytkj.digitalConstruction.httpbean.assets.resbean.ResDevice;
import com.ytkj.digitalConstruction.service.assets.DeviceService;
import com.ytkj.digitalConstruction.util.WebTokenUtil;

/**
 * 控制层 设备管理操作的入口
 * 
 * @author
 * @date 2017年12月1日 下午2:32:20
 * 
 */
@RestController
@RequestMapping("device")
public class DeviceController {

	private Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 设备管理Service
	 */
	@Autowired
	private DeviceService deviceService;

	/**
	 * 增加设备
	 * 
	 * @param device
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("insertDevice")
	public ReturnCode insert(@RequestBody @Valid Device device, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 插入设备
		Integer result = deviceService.insert(device);
		String deviceName = device.getDeviceName();
		if (result == null || result == 0) {
			log.error("添加设备：" + deviceName + "失败");
			return new ReturnCode.Builder().Success(false).Msg("添加失败!").build();
		}
		log.info("添加设备：" + deviceName + "成功");
		return new ReturnCode.Builder().Success(true).Msg("添加成功!").Object(device).build();
	}

	/**
	 * 修改设备
	 * 
	 * @param device
	 * @param bindingResult
	 * @return
	 */
	@Transactional
	@PostMapping("updateDevice")
	public ReturnCode update(@RequestBody @Valid Device device, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		String deviceName = device.getDeviceName();
		String msg = null;
		if (!deviceService.deviceExists(device)) {
			msg = String.format("设备[%s]不存在.", deviceName);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		if (!deviceService.update(device)) {
			msg = String.format("设备[%s]修改失败.", deviceName);
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("修改成功!").build();
	}

	/**
	 * 逻辑删除 删除设备
	 * 
	 * @param id:删除设备的id
	 * 
	 * @return
	 */
	@GetMapping("/deleteDevice/{id}")
	public ReturnCode delete(@PathVariable Integer id) {
		// 判断传入的ID是否为空
		if (id == null || id < 1) {
			log.error("传入的设备id不合法");
			return new ReturnCode.Builder().Success(false).Msg("设备id不为负数!").build();
		}
		// 删除设备
		Integer result = deviceService.delete(id);
		if (result == null || result == 0) {
			log.error("未找到id为" + id + "的设备，删除失败");
			return new ReturnCode.Builder().Success(false).Msg("删除失败!").build();
		}
		log.info("删除设备成功");
		return new ReturnCode.Builder().Success(true).Msg("删除成功!").build();
	}

	/**
	 * 分页查询设备
	 * 
	 * @param pageParam
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/selectDevice")
	public ReturnCode select(HttpServletRequest request, @RequestBody @Valid PageParam pageParam,
			BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		log.info("查询所有设备信息");
		int userId = WebTokenUtil.getUserId(request);
		// 查询所有未删除设备 TODO 分页有BUG
		Page<ResDevice> pageResult = deviceService.select(userId, pageParam);
		PageResult<ResDevice> pageResults = new PageResult<ResDevice>();
		pageResults.setItemTotal(pageResult.getTotal());
		pageResults.setItems(pageResult.getResult());
		log.info("查询所有设备信息成功");
		return new ReturnCode.Builder().Success(true).Msg("查询成功!").Object(pageResults).build();
	}

	/**
	 * 分页查询设备
	 * 
	 * @param pageParam
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/selectDeviceList")
	public ReturnCode selectAll(HttpServletRequest request) {
		int userId = WebTokenUtil.getUserId(request);
		List<ResDevice> devices = deviceService.selectAll(userId);
		return new ReturnCode.Builder().Success(true).Msg("查询成功!").Object(devices).build();
	}

	/**
	 * 查找可绑定设备
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/getBindDevices")
	public HttpResult findBindDevices(HttpServletRequest request) {
		int userId = WebTokenUtil.getUserId(request);
		return new HttpResult().success().obj(deviceService.findBindDevices(userId));
	}

	@GetMapping("/status")
	public HttpResult getStatus() {
		JSONObject jsonObject = new JSONObject();
		AssetStatus[] status = AssetStatus.values();
		for (AssetStatus as : status) {
			if (as == AssetStatus.DELETED) {
				continue;
			}
			jsonObject.put(String.valueOf(as.intVal()), as.string());
		}
		return new HttpResult().success().obj(jsonObject);
	}

}
